package com.demo.datastructure.binarySearch;

/**
 * @author ljr
 * @version 1.0
 * @description: 查找最后一个值等于给定值的元素
 * @date 2021/10/13 17:25
 */
public class BinarySearch14 {

    public static int bsearch(int[] nums, int target) {
        int low = 0;
        int high = nums.length-1, n =  high;
        while(low <= high){
            int mid = low + (high - low >> 1);
            if(nums[mid] > target){
                high = mid - 1;
            }else if(nums[mid] < target){
                low = mid +1;
            }else{
                if(mid == n || nums[mid+1] != target) return mid;
                else low = mid + 1;
            }
        }
        return -1;
    }

    public static int bsearch2(int[] nums, int target) {
        int low = 0;
        int high = nums.length-1, n = high;
        while(low <= high) {
            int mid = low + (high - low >> 1);
            if(nums[mid] <= target){
                low = mid +1;
            }else{
                high = mid -1;
            }
        }
        if(high > 0 && nums[high] == target) return high;
        else return -1;
    }





    public static void main(String[] args) {
        //int[] nums = new int[]{1,3,5};
        int[] nums = new int[]{0,1,2,4,5,5,5};
        int index = BinarySearch14.bsearch2(nums,5);
        System.out.println(index);
    }

}
